import requests
import re
import execjs

headers = {
    'Referer': 'https://www.mafengwo.cn/i/5376978.html',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'
}
url = 'https://www.mafengwo.cn/i/5376978.html'


def first_request():
    response = requests.get(url, headers=headers)
    coo = re.findall("document.cookie=(.*?);location", response.text)[0]
    # cookie取值之后前面的不用
    __jsl_clearance_s = execjs.eval(coo).split('ance_s=')[-1]
    __jsluid_s = response.cookies.get('__jsluid_s')
    return __jsluid_s, __jsl_clearance_s


def second_request():
    __jsluid_s, __jsl_clearance_s = first_request()
    cookies = {'__jsluid_s': __jsluid_s, '__jsl_clearance_s': __jsl_clearance_s}
    res = requests.get(url, headers=headers, cookies=cookies)
    go_code = execjs.eval(re.findall(';go\((.*?)\)</s', res.text)[0])
    # print(go_code)
    js = execjs.compile(open('马蜂窝.js', encoding='utf-8').read())
    __jsl_clearance_s = js.call('go', go_code).split('ance_s=')[-1]
    # print(__jsl_clearance_s)
    cookies['__jsl_clearance_s'] = __jsl_clearance_s
    return cookies


def third_request():
    cookies = second_request()
    res = requests.get(url, headers=headers, cookies=cookies)
    print(res.text)
    print(res.request.headers)


third_request()
